<template>
  <span class="will-box">
    <el-button plain
               class="createWillBtn"
               @click="handleClick">{{title}}</el-button>
    <el-dialog title="创建对账单"
               class="willdialog"
               destroy-on-close
               :close-on-click-modal="false"
               :visible.sync="dialogVisible"
               width="420px"
               @close="closeAddDialog">
      <el-form ref="ruleForm"
               :model="ruleForm"
               :rules="rules"
               label-width="95px"
               class="demo-ruleForm">
        <el-form-item v-if="createType === 1"
                      label="发货方名称"
                      prop="customerName">
          <div>{{ruleForm.customerName}}</div>
          <!-- <el-input v-model="ruleForm.customerName"
                    disabled /> -->
        </el-form-item>
        <el-form-item v-else
                      label="承运方名称"
                      prop="carrierName">
          <div>{{ruleForm.carrierName}}</div>
          <!-- <el-input v-model="ruleForm.carrierName"
                    disabled /> -->
        </el-form-item>
        <el-form-item label="对账单名称"
                      prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="摘要"
                      prop="desc">
          <el-input v-model="ruleForm.desc"
                    type="textarea"
                    placeholder="请输入摘要"
                    :rows="3" />
        </el-form-item>
        <el-form-item label="制单时间"
                      prop="preparationTime">
          <span>{{ruleForm.preparationTime}}</span>
        </el-form-item>
        <div class="btnRuleForm">
          <el-button type="primary"
                     :loading="loading"
                     @click="submitForm('ruleForm')">下一步</el-button>
          <el-button @click="handleCancel()">取消</el-button>
        </div>
      </el-form>
    </el-dialog>
  </span>
</template>

<script>
import { finance } from "@/api/index";
import { mapActions } from "vuex";
import _ from 'lodash'
export default {
  name: 'CreateWill',
  inject: ["$table"],
  props: {
    title: String,
    data: Object,
    url: String
  },
  data () {
    return {
      loading: false,
      dialogVisible: false,
      // diglogShow: false,
      ruleForm: {
        preparationTime: '自动生成制单时间'
      },
      rules: {
        name: [{ required: true, message: '请输入对账单名称', trigger: 'blur' }]
      },
      billId: null
    }
  },
  computed: {
    selection () {
      return this.$table.selection;
    },
    createType () {
      return this.data?.createType
    },
    checkCarrierEquality () {
      return arr => {
        return arr.every((item, index) => {
          return index === 0 || (item.driverId === arr[index - 1].driverId && item.carrierId === arr[index - 1].carrierId);
        });
      }
    },
    checkShipperEquality () {
      return arr => {
        return arr.every((item, index) => {
          return index === 0 || (item.customerId === arr[index - 1].customerId);
        });
      }
    },
    waybillIds () {
      return this.selection.map(billId => billId.waybillId)
    },
    queryParams () {
      return { ...this.data, batchEntry: this.selection }
    }
  },
  methods: {
    ...mapActions({
      routeLink: "link/routeLink"
    }),
    submitForm: _.debounce(function (formName) {    // 触发事件
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.handleCreate()
        } else {
          return false;
        }
      });
    }, 600),

    handleClick () {
      if (this.selection.length > 0) {
        if (this.createType === 1) {
          this.ruleForm.customerName = this.selection[0].customerName
          if (this.checkShipperEquality(this.selection)) {
            this.dialogVisible = true
            // this.diglogShow = true
            // this.createPath()
          } else {
            return this.$message.error('勾选的运单，不是同一个发货方')
          }
        } else if (this.createType === 2) {
          this.ruleForm.carrierName = this.selection[0].carrierName
          if (this.checkCarrierEquality(this.selection)) {
            this.dialogVisible = true
            // this.diglogShow = true
            // this.createPath()
          } else {
            return this.$message.error('勾选的运单，不是同一个承运方或者自营司机')
          }
        }
      } else {
        this.$message.warning({ type: "warning", message: "请选择至少一条数据" });
      }
    },
    createPath ({ billId }) {
      let kwargs = {
        link: this.url,
        target: '',
        query: {
          ...this.data,
          ...this.ruleForm,
          billId: billId,
          // isLabor: true,
          batchEntry: this.selection
        }
      }
      this.routeLink(kwargs)
      this.dialogVisible = false
    },
    async handleCreate () {
      const params = {
        ...this.ruleForm,
        carrierId: this.selection[0].carrierId,
        waybillIds: this.waybillIds,
        customerId: this.selection[0].customerId
      }
      const response = this.queryParams?.createType === 1
        ? await finance.createReceivable(params).catch(() => { this.loading = false; })
        : await finance.createPayable(params).catch(() => { this.loading = false; });
      if (response?.code === 0) {
        this.loading = false;
        const { data } = response;
        this.$message.success("已生成对账单！");
        this.createPath({ billId: data })
        // this.getBillDetail({ ...this.params, billId: data });
      }
    },
    closeAddDialog () {
      this.dialogVisible = false   //关闭对话框
      this.$refs.ruleForm.resetFields();
    },
    handleCancel () {
      this.dialogVisible = false
      // this.diglogShow = false
    }
  }
}
</script>

<style scoped>
.createWillBtn {
  border: 1px solid #dcdfe6;
  color: var(--prev-color-text-regular);
  padding: 9px 10px;
}
.willdialog >>> .el-dialog__header {
  display: flex;
  align-items: center;
}
.willdialog >>> .el-form-item__content {
  text-align: left;
}
.btnRuleForm {
  text-align: center;
}
</style>